import React, { useEffect } from 'react';
import { Form, Input, Button, DatePicker } from 'antd';
import moment from 'moment';

interface ReturnRecord {
  id: number;
  bookName: string;
  borrower: string;
  returnDate: string;
}

interface ReturnRecordFormProps {
  record: ReturnRecord | null;
  onSave: (record: ReturnRecord) => void;
  onCancel: () => void;
}

const ReturnRecordForm: React.FC<ReturnRecordFormProps> = ({ record, onSave, onCancel }) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (record) {
      form.setFieldsValue({
        ...record,
        returnDate: moment(record.returnDate),
      });
    } else {
      form.resetFields();
    }
  }, [record, form]);

  const onFinish = (values: any) => {
    const updatedRecord = {
      ...values,
      returnDate: values.returnDate.format('YYYY-MM-DD'),
    };
    onSave(updatedRecord);
  };

  return (
    <Form form={form} layout="vertical" onFinish={onFinish}>
      <Form.Item name="bookName" label="书名" rules={[{ required: true, message: '请输入书名' }]}>
        <Input />
      </Form.Item>
      <Form.Item name="borrower" label="借阅人" rules={[{ required: true, message: '请输入借阅人' }]}>
        <Input />
      </Form.Item>
      <Form.Item name="returnDate" label="归还日期" rules={[{ required: true, message: '请选择归还日期' }]}>
        <DatePicker />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          保存
        </Button>
        <Button style={{ marginLeft: '8px' }} onClick={onCancel}>
          取消
        </Button>
      </Form.Item>
    </Form>
  );
};

export default ReturnRecordForm;